package com.changyi.accessibilityapidemo;

import android.accessibilityservice.AccessibilityService;
import android.content.res.Resources;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;

/**
 * Created by changyizhang on 5/14/15.
 */
public class ApkInstallAccessibilityService extends AccessibilityService {

  // private static final String TAG = AccessibilityFeedbackService.class.getSimpleName();

  @Override
  public void onAccessibilityEvent(AccessibilityEvent event) {
    if (!SystemPackageInstallerInfo.PACKAGE_INSTALLER_PACKAGE_NAME.equals(event.getPackageName())) {
      return;
    }

    AccessibilityNodeInfo source = event.getSource();
    if (source == null) {
      return;
    }

    Resources resources = getResources();
    if (SystemPackageInstallerInfo.PACKAGE_INSTALLER_ACTIVITY_NAME.equals(event.getClassName())) {
      performClickOnButton(source, resources
          .getText(R.string.install_text).toString());
    }
    if (SystemPackageInstallerInfo.INSTALL_APP_PROGRESS_CLASS_NAME.equals(event.getClassName())) {
      performClickOnButton(source, resources
          .getText(R.string.done_text).toString());
    }
    source.recycle();
  }

  @Override
  public void onInterrupt() {

  }

  // Filter buttons by its show text.
  private void performClickOnButton(AccessibilityNodeInfo source, String text) {
    int childCount = source.getChildCount();
    AccessibilityNodeInfo current;
    for (int index = 0; index < childCount; index++) {
      current = source.getChild(index);
      if (current != null
          && current.getClassName().toString()
              .contains(SystemPackageInstallerInfo.INSTALL_BUTTON_CLASS_NAME)
          && text.equalsIgnoreCase(current.getText().toString())) {
        current.performAction(AccessibilityNodeInfo.ACTION_CLICK);
      } else if (current.getChildCount() > 0) {
        performClickOnButton(current, text);
      }
      current.recycle();
    }
  }

  static class SystemPackageInstallerInfo {
    static final String PACKAGE_INSTALLER_PACKAGE_NAME = "com.android.packageinstaller";
    static final String PACKAGE_INSTALLER_ACTIVITY_NAME = PACKAGE_INSTALLER_PACKAGE_NAME + "."
        + "PackageInstallerActivity";
    static final String INSTALL_APP_PROGRESS_CLASS_NAME = PACKAGE_INSTALLER_PACKAGE_NAME + "."
        + "InstallAppProgress";
    static final String INSTALL_BUTTON_CLASS_NAME = "Button";
  }
}
